package com.xxx.controller;

import com.xxx.controller.ex.*;
import com.xxx.controller.utils.R;
import com.xxx.service.ex.*;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**
 * 控制层的基类 用于统一处理异常
 */
public class BaseController {
    //操作成功状态码
    public static final int OK=200;

    //处理异常 返回信息给前端
    @ExceptionHandler({ServiceException.class, FileUploadException.class})
    public R handleException(Throwable e){
        R result = new R();
        if(e instanceof UsernameException){
            result.setState(4000);
            result.setMsg("用户名已被占用");
        }else if(e instanceof InsertException){
            result.setState(5000);
            result.setMsg("注册出现异常");
        }else if(e instanceof UserNotFoundException){
            result.setState(4001);
            result.setMsg("用户名或密码错误");
        }else if(e instanceof UpdatException){
            result.setState(5001);
            result.setMsg("修改出现异常");
        }else if(e instanceof FileEmptyException){
            result.setState(6000);
            result.setMsg("文件为空");
        }else if(e instanceof FileSizeException){
            result.setState(60001);
            result.setMsg("文件大小出错");
        }else if(e instanceof FileTypeException){
            result.setState(6002);
            result.setMsg("文件类型出错");
        }else if(e instanceof FileUploadIOException){
            result.setState(6004);
            result.setMsg("文件读写时出错");
        }else if(e instanceof FileStateException){
            result.setState(6004);
            result.setMsg("文件状态异常");
        }else if(e instanceof AddressCountLimitException){
            result.setState(7000);
            result.setMsg("用户收货地址超出最大限制");
        }else if(e instanceof AddressNotFoundException){
            result.setState(7001);
            result.setMsg("用户收货地址不存在");
        }else if(e instanceof DeleteException){
            result.setState(8000);
            result.setMsg("删除数据时产生未知异常");
        }else if(e instanceof ProductNotFoundException){
            result.setState(9000);
            result.setMsg("查询单个商品信息时产生未知异常");
        }else if(e instanceof ProductNotFoundException){
            result.setState(9000);
            result.setMsg("查询单个商品信息时产生未知异常");
        }
        return result;
    }
    /**
     * 登录成功返回用户的uid username 存在域中
     */
    protected final Integer getUidFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("uid").toString());
    }
    protected final String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }
}
